package com.ruoyi.message.general.util;

import cn.hutool.http.ssl.TrustAnyHostnameVerifier;
import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Map;

/**
 * @author liyang
 * @apiNote okhttp工具类
 * @date 2021/6/11 11:54
 */
public class OkHttp3Util {

    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String PUT = "PUT";
    public static final String DELETE = "DELETE";
    public static final OkHttpClient okHttpClient;

    static {
        SSLSocketFactory socketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, new SecureRandom());
            socketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            System.exit(-1);
        }
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(Duration.of(10L, ChronoUnit.SECONDS))
                .hostnameVerifier(new TrustAnyHostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .addInterceptor(chain -> {
                    Headers userAgent = chain.request().headers().newBuilder().add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52").build();
                    Request request = chain.request().newBuilder().headers(userAgent).build();
                    return chain.proceed(request);
                })
                .eventListener(new EventListener() {
                    @Override
                    public void callEnd(Call call) {
                        super.callEnd(call);
                    }
                })
                .sslSocketFactory(socketFactory, new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                })
                .build();
    }

    private OkHttp3Util() {
        throw new IllegalStateException();
    }

    public static Response send(String url, Map<String, String> headers, String method, RequestBody requestBody) {
        boolean isRequestBody = false;
        if (requestBody != null) {
            isRequestBody = true;
        }
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (headers != null) {
            builder.headers(Headers.of(headers));
        }
        if (POST.equalsIgnoreCase(method)) {
            builder.post(isRequestBody ? requestBody : null);
        } else if (PUT.equalsIgnoreCase(method)) {
            builder.put(isRequestBody ? requestBody : null);
        } else if (DELETE.equalsIgnoreCase(method)) {
            if (isRequestBody) {
                builder.delete(requestBody);
            } else {
                builder.delete();
            }
        } else {
            builder.get();
        }
        Request request = builder.build();
        try {
            return okHttpClient.newCall(request).execute();
        } catch (Exception e) {
            throw new RuntimeException("okhttp3请求失败");
        }
    }

}
